from audioop import reverse

from django.http import HttpResponse
from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin

"""
定义中间间
应用 中间件
在settings 中MIDDLEWARE 加入中间件路径
process_request方法

# 如果方法中没有返回值（返回None） ，继续往下走
# 如果有返回值  HttpResponse  render  redirect
"""


class Auth(MiddlewareMixin):
    """中间件1"""

    def process_request(self, request):
        # 0.排除不需要登录就能访问的页面
        # request.session.get('info') 获取当前用户请求url
        if request.path_info in ['/ws/index/',  '/account/login/', '/account/img/']:
            return

        # 1.读取当前访问用户的session信息  如果能读到 说明已登录，可以往下走
        info_dict = request.session.get('info')
        if info_dict:
            return

        # 2. 没有登录过，重新回到登录页面
        return redirect('account_login')

        # 如果方法中没有返回值（返回None） ，继续往下走
        # 如果有返回值  HttpResponse  render  redirect
        # print("AuthMiddleware.process_request：" + "来了")
        # return HttpResponse("无权访问")

    def process_response(self, request, response):
        # print("AuthMiddleware:" + "走了")
        # print(request)
        # print(response)
        return response

# class M1(MiddlewareMixin):
#     """中间件1"""
#
#     def process_request(self, request):
#         print("M1：" + "来了")
#
#     def process_response(self, request, response):
#         print("M1:" + "走了")
#         return response

# class M2(MiddlewareMixin):
#     """中间件1"""
#
#     def process_request(self, request):
#         print("M2：" + "来了")
#
#     def process_response(self, request, response):
#         print("M2:" + "走了")
